package two.chapter_1.c1_3;

import java.util.Iterator;

public class CircularLinkedQueue<Item> implements Queue<Item> {
    private int size;
    private Node last;//最后一个结点
    @Override
    public void enqueue(Item item) {
        Node node=new Node(item);
        if (isEmpty()){
            last=node;
            last.next=last;
        }else {
            node.next=last.next;
            last.next=node;
            last=node;
        }
        size++;
    }

    @Override
    public Item dequeue() {
        if (isEmpty()){
            throw new CollectionEmptyException();
        }
        Item item;
        if (size==1){
            item=last.item;
            last=null;
        }else {
            item=last.next.item;
            last.next=last.next.next;
        }
        size--;
        return item;
    }

    @Override
    public boolean isEmpty() {
        return size()==0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Iter();
    }

    private class Node{
        Item item;
        Node next;
        public Node(Item item){
            this.item=item;
        }
    }

    private class Iter implements Iterator<Item>{
        private Node next=last.next;
        private int count=size;
        @Override
        public boolean hasNext() {
            return count>0;
        }

        @Override
        public Item next() {
            count--;
            Item item=next.item;
            next=next.next;
            return item;
        }

        @Override
        public void remove() {

        }
    }
}
